﻿using FR.CodeVisualizer.ObjectSource;
using FR.CodeVisualizer.Views;
using FR.CodeVisualizer.Visualizers;
using Microsoft.VisualStudio.DebuggerVisualizers;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Windows.Forms;

[assembly: System.Diagnostics.DebuggerVisualizer(
    typeof(EFDbContextVisualizer), typeof(EFDbContextVisualizerObjectSource), Target = typeof(DbContext), Description = "FR Visualizers - DbContext")]
[assembly: System.Diagnostics.DebuggerVisualizer(
    typeof(EFDbContextVisualizer), typeof(EFDbContextVisualizerObjectSource), Target = typeof(DbQuery), Description = "FR Visualizers - DbContext")]
[assembly: System.Diagnostics.DebuggerVisualizer(
    typeof(EFDbContextVisualizer), typeof(EFDbContextVisualizerObjectSource), Target = typeof(DbQuery<>), Description = "FR Visualizers - DbContext")]

namespace FR.CodeVisualizer.Visualizers
{
    public class EFDbContextVisualizer : DialogDebuggerVisualizer
    {
        public static void TestShowVisualizer(object objectToVisualize)
        {
            VisualizerDevelopmentHost visualizerHost = new VisualizerDevelopmentHost(objectToVisualize, typeof(EFDbContextVisualizer), typeof(EFDbContextVisualizerObjectSource), true);
            visualizerHost.ShowVisualizer();
        }

        protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
        {
            if (windowService == null)
                throw new ArgumentNullException("windowService");
            if (objectProvider == null)
                throw new ArgumentNullException("objectProvider");

            SQLQueryOptions sqlOptions = objectProvider.GetObject() as SQLQueryOptions;

            if (sqlOptions != null)
            {
                //inicializar o visualizador
                using (FormMainTextEdit main = new FormMainTextEdit())
                {
                    main.Init(sqlOptions.SQLCommand, text: " - EF DbContext Visualizer", connectionString: sqlOptions.ConnectionString, showSqlPanel: sqlOptions.IsQuery);
                    main.SetLanguage(SupportedLanguage.SQL);
                    if (!string.IsNullOrEmpty(sqlOptions.ExceptionMessage))
                        main.SetExceptionMessage(sqlOptions.ExceptionMessage);

                    //mostrar o visualizer
                    DialogResult dr = windowService.ShowDialog(main);

                    if (objectProvider.IsObjectReplaceable && dr == DialogResult.OK)
                        objectProvider.ReplaceObject(sqlOptions);
                }
            }
        }
    }
}
